import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter_device_info_plugin/flutter_device_info_plugin.dart';
import 'package:furaha_mkopo/commonTool/fm_time_tool.dart';
import 'package:furaha_mkopo/commonUI/fm_progress_hud.dart';
import 'package:furaha_mkopo/commonUI/fm_toast.dart';
import 'package:furaha_mkopo/page/home/orderDetail/emergency/fm_emergency_save_api.dart';
import 'package:geolocator/geolocator.dart';
import 'package:get/get.dart';

import '../../../../commonTool/fm_report_event_tool.dart';
import '../../controller/fm_common_controller.dart';
import 'fm_emergency_api.dart';
import 'fm_emergency_model.dart';
import 'fm_emergency_report_contact_api.dart';

class FMEmergencyController extends GetxController {

  List<FMEmergencyStartedModel>? dataSource;

  List<Map<String,dynamic>> uploadData = [];

  String orderId = "";

  Position? position;

  int startTime = 0;

  @override
  void onInit() {
    super.onInit();
    startTime = FMTimeTool.currentTime;
  }

  void refreshData(String orderId) {
    this.orderId = orderId;
    FMEmergencyApi api = FMEmergencyApi(orderId: orderId);
    api.send<FMEmergencyModel,FMEmergencyModel>(decodeType: FMEmergencyModel()).then((value){
      FMProgressHud.hideLoading();
      if (value.code == 0) {
        dataSource = value.data?.started;

        for (FMEmergencyStartedModel model in dataSource!) {
          Map<String,dynamic> dic = {};

          String? planned = model.planned;
          String? advertisement = model.advertisement;
          String? suspense = model.suspense;
          dic["advertisement"] = advertisement;
          dic["suspense"] = suspense;
          dic["planned"] = planned;

          uploadData.add(dic);
        }
        update();
      }
    });
  }

  void saveData(BuildContext context,bool? isOldPage) {

    String jsonString = jsonEncode(uploadData);

    FMEmergencySaveApi api = FMEmergencySaveApi(
      orderId: orderId,
      json: jsonString
    );
    FMProgressHud.showLoading();
    api.send().then((value){
      FMProgressHud.hideLoading();
      if (value.code == 0) {
        reportRisk();

        if (isOldPage == true) {
          Navigator.pop(context);
          return;
        }

        final controller = Get.put(FMCommonController());
        controller.onRequestNoEmptyListen(context, orderId);
      }else {
        FMToast.showText(value.message ?? "Network request error");
      }
    });
  }

  void reportTotalContactInfo() async {

    dynamic list = await FlutterDeviceInfoPlugin().getContactInfo();

    FMEmergencyReportContactApi api = FMEmergencyReportContactApi(
      json: jsonEncode(list)
    );

    api.send().then((value) {});
  }

  String titleAtIndex(int index) {
    FMEmergencyStartedModel? model = startedModelAtIndex(index);
    return model?.soul ?? "";
  }

  String relationTitleAtIndex(int index) {
    FMEmergencyStartedModel? model = startedModelAtIndex(index);
    return model?.torturing ?? "";
  }

  String relationPlaceHolderAtIndex(int index) {
    FMEmergencyStartedModel? model = startedModelAtIndex(index);
    return model?.incessant ?? "";
  }

  String phoneTitleAtIndex(int index) {
    FMEmergencyStartedModel? model = startedModelAtIndex(index);
    return model?.relief ?? "";
  }

  String phonePlaceHolderAtIndex(int index) {
    FMEmergencyStartedModel? model = startedModelAtIndex(index);
    return model?.abandoned ?? "";
  }

  String relationContentAtIndex(int index) {
    if (index >= uploadData.length) return "";

    Map<String,dynamic> map = uploadData[index];

    List<FMEmergencyRetiredModel>? list = retiredListAtIndex(index);

    if (list == null || list.isEmpty) return "";

    String? value = map["advertisement"];

    String relationContent = "";

    for (FMEmergencyRetiredModel model in list) {
      if (model.firm == value) {
        relationContent = model.planned ?? "";
        break;
      }
    }

    return relationContent;
  }

  String contactContentAtIndex(int index) {
    if (index >= uploadData.length) return "";
    Map<String,dynamic> map = uploadData[index];

    String name = map["planned"] ?? "";
    String phone = map["suspense"] ?? "";

    if (name.isNotEmpty && phone.isNotEmpty) {
      return "$name $phone";
    }else if (name.isNotEmpty) {
      return name;
    }else if (phone.isNotEmpty){
      return phone;
    }else {
      return "";
    }
  }

  void updateRelationDic(int index,String title) {
    if (index >= uploadData.length) return;

    List<FMEmergencyRetiredModel>? list = retiredListAtIndex(index);

    if (list == null || list.isEmpty) return;

    String value = "";

    for (FMEmergencyRetiredModel model in list) {
      if (model.planned == title) {
        value = model.firm ?? "";
        break;
      }
    }

    uploadData[index]["advertisement"] = value;

    update();
  }

  void updateContactDic(int index,String name,String phone) {
    if (index >= uploadData.length) return;

    uploadData[index]["planned"] = name;

    uploadData[index]["suspense"] = phone;

    update();
  }


  List<FMEmergencyRetiredModel>? retiredListAtIndex(int index) {
    FMEmergencyStartedModel? model = startedModelAtIndex(index);

    List<FMEmergencyRetiredModel>? list = model?.retired;

    return list;
  }

  FMEmergencyStartedModel? startedModelAtIndex(int index) {
    if (dataSource == null) return null;
    if (index >= dataSource!.length) return null;

    return dataSource![index];
  }

  void reportRisk() {
    int endTime = FMTimeTool.currentTime;
    FMReportEventTool.reportRisk("7", position?.latitude, position?.longitude, startTime, endTime);
  }
}